package battle_system

import (
	"confs/gen/common"
	"game/app/actors/schemas"
	"gos/bases/parse"
	"gos/modules/logger"
)

// BattlerSettleSystem
type BattlerSettleSystem struct{}

type IBattlerSettleSystem interface {
	SettleBattleEnd(state *schemas.MoveState)
	SettleLossTroop(state *schemas.MoveState) error
}

var BattlerSettle IBattlerSettleSystem = BattlerSettleSystem{}

// SettleBattleEnd 结算战斗结束
func (s BattlerSettleSystem) SettleBattleEnd(state *schemas.MoveState) {
	reports := []*common.BattleReport{}
	for _, battle := range state.DestorySettleBattles {
		report := &common.BattleReport{
			Attack: &common.BattleReportRound{
				Id:               battle.A.Id,
				UserId:           battle.A.UserId,
				Type:             battle.A.Type,
				IsDead:           battle.A.IsDead,
				DeadSoldiers:     battle.A.AcumulateLossSoldiders,
				SlightSoldiers:   []*common.BattleTroopSoldier{},
				SinjuredSoldiers: []*common.BattleTroopSoldier{},
				InitSoldiers:     battle.B.TroopCom.InitSoldiers,
				RemainSoldiers:   battle.A.TroopCom.TotalSoldiers,
				Postition:        battle.A.Position.ToVector2D(),
				Direction:        battle.A.Direction.ToVector2D(),
			},

			Defence: &common.BattleReportRound{
				Id:               battle.B.Id,
				UserId:           battle.B.UserId,
				Type:             battle.B.Type,
				IsDead:           battle.B.IsDead,
				DeadSoldiers:     battle.B.AcumulateLossSoldiders,
				SlightSoldiers:   []*common.BattleTroopSoldier{},
				SinjuredSoldiers: []*common.BattleTroopSoldier{},
				InitSoldiers:     battle.B.TroopCom.InitSoldiers,
				RemainSoldiers:   battle.B.TroopCom.TotalSoldiers,
				Postition:        battle.B.Position.ToVector2D(),
				Direction:        battle.B.Direction.ToVector2D(),
			},

			CurTime:  battle.CurTime,
			BattleId: battle.BattleId,
			ServerId: parse.ToInt64(state.SceneId),
		}

		if battle.A.GetTotalSoldierNum() == battle.B.GetTotalSoldierNum() {
			report.Type = common.BattleVictoryType_Draw
		} else {
			if report.Attack.IsDead {
				report.Type = common.BattleVictoryType_Lose
			} else {
				report.Type = common.BattleVictoryType_Win
			}
		}

		// 暂定结算bug，以后修改为A维护的多个战斗关系累加扣血
		battle.A.ClearAcumulateLossSoldier()
		battle.B.ClearAcumulateLossSoldier()
		reports = append(reports, report)
		// 这里彻底销毁战斗所有数据
		Battles.DestoryBattle(state, battle.A, battle.B)
	}

	if len(reports) > 0 {
		BattleBehavior.BattleEndNotice(state, state.SceneId, reports)
	}
}

// mergeBattleRoundRelation 合并玩家所有战斗关系，组成一个战局
func (s BattlerSettleSystem) mergeBattleRoundRelation(battleRounds map[int64]*common.BattleRound, roundRelations map[int64]int64, battleRelations []*common.BattleRelation) {
	for _, rel := range battleRelations {
		_, ok := roundRelations[rel.Id]
		if ok {
			continue
		}

		br, ok := battleRounds[rel.Id]
		if !ok {
			continue
		}

		roundRelations[rel.Id] = rel.Id
		s.mergeBattleRoundRelation(battleRounds, roundRelations, br.Relations)
	}
}

// SettleLossTroop 结算回合单位
func (s BattlerSettleSystem) SettleLossTroop(state *schemas.MoveState) error {
	battleRounds := map[int64]*common.BattleRound{}
	for _, battleEntity := range state.DestorySettleRoundLossTroop {
		battleEntityIds := state.GetBattleEntityId(battleEntity.Id)
		if battleEntityIds == nil {
			logger.ERR("BattleEntityIds没有找到:", battleEntity.Id)
			continue
		}

		battleRelations := []*common.BattleRelation{}
		for _, battle := range battleEntityIds {
			if battle.A.Id != battleEntity.Id {
				battleRelations = append(battleRelations, &common.BattleRelation{
					Id:   battle.A.Id,
					Type: battle.A.Type,
				})
			}

			if battle.B.Id != battleEntity.Id {
				battleRelations = append(battleRelations, &common.BattleRelation{
					Id:   battle.B.Id,
					Type: battle.B.Type,
				})
			}
		}

		moveSlot := false
		battleAIEntity := state.GetBattleAIEntity(battleEntity.Id)
		if battleAIEntity != nil && battleAIEntity.Status == common.BattleEntityAIStatus_AIStatusMovePos {
			moveSlot = true
		}

		battleRounds[battleEntity.Id] = &common.BattleRound{
			Id:               battleEntity.Id,
			UserId:           battleEntity.UserId,
			Type:             battleEntity.Type,
			IsDead:           battleEntity.IsDead,
			DeadSoldiers:     battleEntity.LossSoldiders,
			InitSoldiers:     battleEntity.TroopCom.InitSoldiers,
			KillSoldiers:     []*common.BattleTroopSoldier{},
			SinjuredSoldiers: []*common.BattleTroopSoldier{},
			RemainSoldiers:   battleEntity.TroopCom.TotalSoldiers,
			RegionId:         0,
			Rage:             0,
			Relations:        battleRelations,
			Postition:        battleEntity.Position.ToVector2D(),
			//Direction:        direction.ToVector2D(),
			ServerId: parse.ToInt64(state.SceneId),
			// BattleId: battleId,
			MoveSlot: moveSlot,
		}

		battleEntity.ClearLossSoldier()
	}

	if len(battleRounds) > 0 {
		roundPipes := []*common.BattleRoundPipe{}
		for _, br := range battleRounds {
			roundRelations := map[int64]int64{}
			s.mergeBattleRoundRelation(battleRounds, roundRelations, br.Relations)
			battleRoundRelations := []*common.BattleRound{}
			for id, rr := range roundRelations {
				round, ok := battleRounds[id]
				if !ok {
					logger.ERR("没有找到合并后的战斗关系:", id, rr)
					continue
				}
				// 相关战斗关系，组成一个战局
				battleRoundRelations = append(battleRoundRelations, round)
				// 删除掉已经找到的战斗关系
				delete(battleRounds, id)
			}

			if len(battleRoundRelations) > 0 {
				roundPipes = append(roundPipes, &common.BattleRoundPipe{
					Rounds: battleRoundRelations,
				})
			}
		}

		// 批量发送多个战局
		return BattleBehavior.BattleRoundNotice(state, state.SceneId, roundPipes)
	}
	return nil
}
